package com.cgt.xiaotao.auth.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.cgt.xiaotao.auth.util.JwtTool;
import com.cgt.common.domain.dto.LoginUserDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "认证服务")
@Slf4j
@RestController
@RequestMapping
@RequiredArgsConstructor
public class JwksController {

    private final JwtTool jwtTool;

    @ApiOperation("获取JWT公钥")
    @GetMapping("/jwks")
    public String getJwks() {
        try {
            // 获取公钥并进行Base64编码
            PublicKey publicKey = jwtTool.getPublicKey();
            byte[] encoded = publicKey.getEncoded();
            return Base64.encode(encoded);
        } catch (Exception e) {
            log.error("获取公钥失败", e);
            throw new RuntimeException("获取公钥失败", e);
        }
    }

    @ApiOperation("测试JWT生成和验证")
    @PostMapping("/test-jwt")
    public Object testJwt(@RequestBody LoginUserDTO userDTO) {
        try {
            // 确保传入的userDTO包含必要信息
            log.info("接收到的用户信息: {}", userDTO);
            if (userDTO.getUserId() == null) {
                userDTO.setUserId(1L); // 设置默认用户ID
            }
            if (userDTO.getRoleId() == null) {
                userDTO.setRoleId(2L); // 设置默认角色ID
            }
            userDTO.setRememberMe(false); // 设置记住我标志

            // 生成JWT
            String token = jwtTool.createToken(userDTO);
            log.info("生成的JWT token: {}", token);

            // 验证JWT - 使用公钥验证签名
            cn.hutool.jwt.signers.JWTSigner signer = JWTSignerUtil.createSigner("RS256", jwtTool.getPublicKey());
            JWT jwt = JWT.of(token).setSigner(signer);
            boolean verifyResult = jwt.verify();
            log.info("本地验证结果: {}", verifyResult);

            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("verifyResult", verifyResult);
            return result;
        } catch (Exception e) {
            log.error("JWT测试失败", e);
            throw new RuntimeException("JWT测试失败", e);
        }
    }
}
